package com.chat.chat.controller;

import com.chat.chat.beans.ChatVo;
import com.chat.chat.beans.User;
import com.chat.chat.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    RedisCache redisCache;


    @GetMapping("getUser")
    public List<ChatVo> getUser() {

        List<Integer> userList = redisCache.getCacheList("home:user");
        ArrayList<ChatVo> vos = new ArrayList<>();

        for (Integer integer : userList) {
            ChatVo chatVo = new ChatVo();
            chatVo.setId(integer);
            chatVo.setType("3");
            chatVo.setMsg("用户"+integer+"有新消息");
            chatVo.setNowTime(new Date());
            vos.add(chatVo);
        }
        return vos;
    }

    @PostMapping("setUser")
    public long SetUser(@RequestBody User user) {
        List<Integer> ids = user.getUsers().stream().map(item -> item.getId()).collect(Collectors.toList());
        List<Integer> useList = redisCache.getCacheList("home:user");
        ArrayList<Integer> list = new ArrayList<>();
        if (!useList.isEmpty()){
            for (Integer id : ids) {
                if (!useList.contains(id)){
                    list.add(id);
                }
            }
        }else {
            long l = redisCache.setCacheList("home:user", ids);
            redisCache.expire("useList", 5, TimeUnit.HOURS);
        }
        if (!list.isEmpty()){
            long l = redisCache.setCacheList("home:user", list);
            redisCache.expire("useList", 15, TimeUnit.HOURS);
            return l;
        }

        return 1;
    }


}
